package com.rf.richfitwheel.workflow.controller;

import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.admin.feignclient.FSysUserService;
import com.rf.richfitwheel.admin.sys.model.User;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.workflow.entity.ProcessDeleteParam;
import com.rf.richfitwheel.workflow.entity.WfTaskParam;
import com.rf.richfitwheel.workflow.entity.WfTaskVo;
import com.rf.richfitwheel.workflow.model.WfProcessTask;
import com.rf.richfitwheel.workflow.service.WfProcessService;
import com.rf.richfitwheel.workflow.service.WfProcessTaskService;
import com.rf.richfitwheel.workflow.service.WfTaskService;
import net.sf.json.JSONObject;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/wftask")
@RestController
public class WfTaskController {

    protected static final Logger log = LoggerFactory.getLogger(WfTaskController.class);
    @Autowired
    private WfTaskService wfTaskService;

    @Autowired
    private WfProcessService wfProcessService;

    @Autowired
    private WfProcessTaskService wfProcessTaskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private FSysUserService fSysUserService;


    /**
     * <p>Title: 流程提交方法，供前端和外部feign调用</p>
     * <p>Description: </p>
     *
     * @param wfTaskParam
     * @return
     */
    @UserOperateLog(module = "工作流", methods = "submitTask", description = "提交流程", functionNo = "104016")
    @PostMapping(value = "/submitTask")
    @ResponseBody
    public R submitTask(@RequestBody WfTaskParam wfTaskParam) {
        try {
            UserVO user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
//            return wfTaskService.submitTask(wfTaskParam, user);
            WfTaskParam wfp = wfTaskService.submitTask(wfTaskParam, user);
            return R.ok().put("wfTaskParam", wfTaskParam);
        } catch (ActivitiObjectNotFoundException ex) {
            log.error(ex.getMessage(), ex);
            return R.error("流程未配置或任务已被他人提交！");
        } catch (IllegalArgumentException | BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch(ScriptException e) {
            log.error(e.getMessage(), e);
            return R.error("授权规则配置不正确");
        } catch (Exception e) {
            log.error(" 流程提交失败", e);
            return R.error("流程提交失败");
        }

    }

    /**
     * <p>Title: 流程提交方法，供前端和外部feign调用</p>
     * <p>Description: </p>
     *
     * @param params 流程参数
     * @return 成功状态
     */
    @UserOperateLog(module = "工作流", methods = "submitTaskBatch", description = "批量提交流程", functionNo = "104017")
    @PostMapping(value = "/submitTaskBatch")
    public R submitTaskBatch(@RequestBody List<WfTaskParam> params) {
        UserVO user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
        try {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < params.size(); i++) {
                try {
                    wfTaskService.submitTask(params.get(i), user);
                } catch (ActivitiObjectNotFoundException ex) {
                    log.error("第" + (i + 1) + "条流程未配置或任务已被他人提交！", ex);
                    sb.append("第").append((i + 1)).append("条流程未配置或任务已被他人提交;");
                } catch (BusinessException e) {
                    log.error("第" + (i + 1) + "条记录" + e.getMessage(), e);
                    sb.append("第").append((i + 1)).append("条记录").append(e.getMessage()).append(";");
                } catch(ScriptException e) {
                    log.error("第" + (i + 1) + "条记录" + e.getMessage(), e);
                    sb.append("第").append((i + 1)).append("条记录授权规则配置不正确;");
                } catch (Exception e) {
                    log.error("第" + (i + 1) + "条记录流程提交失败", e);
                    sb.append("第").append((i + 1)).append("条记录流程提交失败;");
                }
            }
            if(sb.length() == 0){
                return R.ok();
            }else{
                return R.error(sb.toString());
            }
        } catch (Exception e) {
            log.error(" 流程提交失败", e);
            return R.error("流程提交失败");
        }

    }

    /**
     * <p>Title: 流程提交方法，供前端和外部feign调用</p>
     * <p>Description: </p>
     *
     * @param wfTaskParam
     * @return
     */
    @UserOperateLog(module = "工作流", methods = "submitTask", description = "提交流程", functionNo = "104016")
    @PostMapping(value = "/submitTaskForMq")
    @ResponseBody
    public R submitTaskForMq(@RequestBody WfTaskParam wfTaskParam) {
        try {
            UserVO userVO = wfTaskParam.getUserVO();
            WfTaskParam wfp = wfTaskService.submitTaskForMq(wfTaskParam, userVO);
            return R.ok().put("wfTaskParam", wfTaskParam);
        } catch (ActivitiObjectNotFoundException ex) {
            log.error(ex.getMessage(), ex);
            return R.error("流程未配置或任务已被他人提交！");
        } catch (IllegalArgumentException | BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch(ScriptException e) {
            log.error(e.getMessage(), e);
            return R.error("授权规则配置不正确");
        } catch (Exception e) {
            log.error(" 流程提交失败", e);
            return R.error("流程提交失败");
        }

    }

    /**
     * 流程查询、分页
     *
     * @param params
     * @return
     */
    @PostMapping("/queryProcessList")
    public R queryProcessList(@RequestBody Map<String, Object> params) {
        PageUtils pageUtils = wfProcessService.queryProcessList(params, UserUtil.getUser());
        return R.ok().put("page", pageUtils);
    }

    /**
     * 我的待办流程
     *
     * @param params
     * @return
     */
    @GetMapping("/todoList")
    public PageUtils todoList(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        UserVO user = UserUtil.getUser();
        String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型
        params.put("moduleType", moduleType);
        PageUtils pageUtils = wfTaskService.getToDoList(params, user);
        return pageUtils;
    }

    /**
     * <p>Title: 我参与的流程</p>
     * <p>Description: </p>
     *
     * @param page
     * @param limit
     * @param dataForm
     * @return
     */
    @GetMapping("/queryPartakeList")
    PageUtils queryPartakeList(String page, String limit, String dataForm, HttpServletRequest request) {
        UserVO user = UserUtil.getUser();
        // List<Map<String, Object>> result = new LinkedList<Map<String, Object>>();

        if (user == null) {
            return null;
        }
        String userId = user.getId();
        String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型
        // 查询我参与的流程
        PageUtils pageUtils = wfProcessService.queryPartakeList(page, limit, dataForm, userId, moduleType);

        return pageUtils;
    }

    /**
     * 我发起的流程查询
     * <p>Title: creatTaskList</p>
     * <p>Description: </p>
     *
     * @param params
     * @return
     */
    @GetMapping("/queryCreateList")
    PageUtils createProcessList(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        try {
            UserVO user = UserUtil.getUser();
            String userId = user.getId();
            int page = Integer.parseInt(params.get("page") != null ? params.get("page").toString() : "0");
            int limit = Integer.parseInt(params.get("limit") != null ? params.get("limit").toString() : "0");
            JSONObject obj = StringUtils.isBlank(params.get("dataForm")) ? null : JSONObject.fromObject(params.get("dataForm"));
            String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型
            obj.put("moduleType", moduleType);
            PageUtils pageUtils = wfProcessService.queryCreateList(page, limit, obj, userId);
            return pageUtils;
        } catch (NumberFormatException e) {
            log.error(e.getMessage(), e);
            return new PageUtils();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new PageUtils();
        }
    }

    /**
     * 获取审批用户
     *
     * @param params
     * @return
     */
    @GetMapping("/getApproveUsers")
    public R getApproveUsers(@RequestParam Map<String, Object> params) {
        List<User> users = new ArrayList<>();
        JSONObject jsonObject = JSONObject.fromObject(params);
        String taskId = jsonObject.getString("taskId");
        String orgCode = jsonObject.getString("orgCode");
        String processCode = jsonObject.getString("processCode");
        String firstNodeUser = jsonObject.containsKey("firstNodeUser") ? jsonObject.getString("firstNodeUser") : "0";
        JSONObject variables = new JSONObject();
        ProcessDefinitionEntity processDefinitionEntity = null;
        ActivityImpl nowActivity = null;
        if (jsonObject.containsKey("variables")) {
            variables = JSONObject.fromObject(jsonObject.getString("variables"));
        }
        if (StringUtils.isBlank(taskId)) {
            processDefinitionEntity = (ProcessDefinitionEntity) repositoryService.createProcessDefinitionQuery().orgCode(orgCode).processCode(processCode).latestVersion().singleResult();
            ActivityImpl firstActivity = wfProcessService.getFirstUserTask(processDefinitionEntity);
            if (ObjectUtils.isEmpty(firstActivity)) {
                return R.ok().put("finishProcess", "1").put("users", users);
            } else {
                nowActivity = firstActivity;
            }
        } else {
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            processDefinitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(task.getProcessDefinitionId());
            nowActivity = processDefinitionEntity.findActivity(task.getTaskDefinitionKey());
        }
        if(Constant.COMMON_YES_OR_NO_YES.equals(firstNodeUser)){
            //直接取第一个节点的审批人
            WfProcessTask wfProcessTask = wfProcessTaskService.findByProDefIdAndTaskDefKey(processDefinitionEntity.getId(), nowActivity.getId());
            if (!ObjectUtils.isEmpty(wfProcessTask)) {
                String assigneeType = wfProcessTask.getAssigneeType();
                if (assigneeType.equals("3")) {
                    String stationIds = wfProcessTask.getCandidateIds();
                    users = fSysUserService.getUserListByStationIds(stationIds);
                }
                return R.ok().put("finishProcess", "0").put("users", users);
            } else {
                return R.ok().put("finishProcess", "1").put("users", users);
            }
        }
        List<ActivityImpl> activities = wfProcessService.findNextUserTaskActivitys(nowActivity, variables);
        if (activities.size() > 0) {
            WfProcessTask wfProcessTask = wfProcessTaskService.findByProDefIdAndTaskDefKey(processDefinitionEntity.getId(), activities.get(0).getId());
            if (!ObjectUtils.isEmpty(wfProcessTask)) {
                String assigneeType = wfProcessTask.getAssigneeType();
                if (assigneeType.equals("3")) {
                    String stationIds = wfProcessTask.getCandidateIds();
                    users = fSysUserService.getUserListByStationIds(stationIds);
                }
                return R.ok().put("finishProcess", "0").put("users", users);
            } else {
                return R.ok().put("finishProcess", "1").put("users", users);
            }
        } else {
            return R.ok().put("finishProcess", "1").put("users", users);
        }
    }

    /**
     * 回退任务列表
     *
     * @param params
     * @return
     */
    @GetMapping("/getBackTasks")
    public R getBackTasks(@RequestParam Map<String, Object> params) {
        String taskId = params.get("taskId") == null ? null : params.get("taskId").toString();
        List<Map<String, Object>> backTasks = wfProcessService.getBackTasks(taskId);
        return R.ok().put("backTasks", backTasks);

    }

    /**
     * 任务跳转（包括回退和向前）至指定活动节点
     *
     * @param currentTaskId
     * @param targetTaskId
     * @return
     * @throws Exception
     */
    @UserOperateLog(module = "工作流", methods = "doBack", description = "流程退回", functionNo = "")
    @RequestMapping(value = "/doBack")
    @ResponseBody
    public R doBack(@RequestParam("taskId") String currentTaskId, @RequestParam("targetTaskId") String targetTaskId, @RequestParam("approveMessage") String approveMessage) throws Exception {
        try {
            UserVO user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
            if(StringUtils.isBlank(targetTaskId))
                throw new BusinessException("请选择想要退回的节点");
            this.wfProcessService.doBackward(currentTaskId, targetTaskId, approveMessage);
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        }catch (Exception e) {
            log.error("退回流程失败！");
            return R.error("退回流程失败！");
        }
        return R.ok("退回成功");
    }

    /**
     * 根据流程实例id查询当前用户参与过的节点，不包含撤回和终止的节点
     *
     * @param processInstanceId 流程实例id
     * @return
     */
    @GetMapping(value = "/getCanRecallTasks/{processInstanceId}")
    public R getCanRecallTasks(@PathVariable("processInstanceId") String processInstanceId) {
        List<Map<String, Object>> list = this.wfTaskService.getCanRecallTasks(processInstanceId, UserUtil.getUser());
        return R.ok().put("recallList", list);
    }

    /**
     * 参与人撤回流程
     *
     * @param params {'processId': 流程实例id,
     *               'recallNodeKey': 要撤回的节点key,
     *               'deleteReason': 撤回原因
     *               }
     * @return
     * @throws Exception
     */
    @UserOperateLog(module = "工作流", methods = "recallMaster", description = "撤回流程")
    @GetMapping("/recall")
    public R recallMaster(@RequestParam Map<String, Object> params) throws Exception {
        try {
            this.wfProcessService.recall(params, UserUtil.getUser(), UserUtil.getSystem());
            return R.ok();
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.error("流程撤回失败！");
        }
    }

    /**
     * 发起人撤回
     * <p>Title: restart</p>
     * <p>Description: </p>
     *
     * @param params
     * @return
     * @throws Exception
     */
    @UserOperateLog(module = "工作流", methods = "restart", description = "发起人撤回流程")
    @GetMapping("/restart")
    public R restart(@RequestParam Map<String, Object> params) throws Exception {
        String processInstanceId = params.get("processInstanceId") != null ? params.get("processInstanceId").toString() : "";
        UserVO user = UserUtil.getUser();
        if (user == null) {
            return R.error("获取用户信息失败！");
        }
        try {
            this.wfProcessService.restartByCreater(processInstanceId, user);
            return R.ok();
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("流程撤回失败", e);
            return R.error("流程撤回失败！");
        }
    }

    /**
     * 发起人撤回,根据业务主键撤回
     *
     * @param businessKey
     * @return
     * @throws Exception
     */
    @UserOperateLog(module = "工作流", methods = "restart", description = "发起人撤回流程")
    @GetMapping("/restartByBusinessKey")
    public R restartByBusinessKey(@RequestParam String businessKey) throws Exception {
        try {
            UserVO user = UserUtil.getUser();
            if (user == null) {
                return R.error("获取用户信息失败");
            }
            this.wfProcessService.restartByBusinessKey(businessKey, user);
            return R.ok();
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("流程撤回失败", e);
            return R.error("流程撤回失败！");
        }
    }

    /**
     * 删除运行中流程
     * <p>Title: deleteProcess</p>
     * <p>Description: </p>
     *
     * @param params
     * @return
     */
    @UserOperateLog(module = "工作流", methods = "deleteProcess", description = "终止流程流程")
    @GetMapping("/deleteProcess")
    public R deleteProcess(@RequestParam Map<String, Object> params) {
        String processid = params.get("processInstanceId") != null ? params.get("processInstanceId").toString() : "";

        String deleteReason = params.get("deleteReason") != null ? params.get("deleteReason").toString() : "";

        try {
            this.wfProcessService.deleteProcess(processid, deleteReason, UserUtil.getUser());
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("流程终止失败", e);
            return R.error("终止失败！");
        }
        return R.ok();
    }

    /**
     * 批量删除运行中流程
     * <p>Title: deleteProcess</p>
     * <p>Description: </p>
     *
     * @param params 参数
     * @return 返回
     */
    @UserOperateLog(module = "工作流", methods = "deleteProcessBatch", description = "批量终止流程")
    @PostMapping("/deleteProcessBatch")
    public R deleteProcessBatch(@RequestBody List<ProcessDeleteParam> params) {
        UserVO user = UserUtil.getUser();
        int x = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            try {
                this.wfProcessService.deleteProcess(params.get(i).getProcessInstanceId(), params.get(i).getDeleteReason(), user);
                x++;
            } catch (BusinessException e) {
                log.error("第" + (i + 1) + "条流程终止失败：" + e.getMessage() + ";", e);
                sb.append("第").append(i + 1).append("条流程终止失败：").append(e.getMessage()).append(";");
            } catch (Exception e) {
                log.error("第" + (i + 1) + "条流程终止失败", e);
                sb.append("第").append(i + 1).append("条流程终止失败").append(";");
            }
        }
        return R.ok("终止流程完成，共成功终止" + x + "条流程，失败" + (params.size() - x) + "条流程。" + sb.toString());
    }

    /**
     * 删除运行中流程
     * <p>Title: deleteProcess</p>
     * <p>Description: </p>
     *
     * @param params
     * @return
     */
    @UserOperateLog(module = "工作流", methods = "deleteProcessByBusinessKey", description = "终止流程流程")
    @GetMapping("/deleteProcessByBusinessKey")
    public R deleteProcessByBusinessKey(@RequestParam Map<String, Object> params) {
        String businessKey = params.get("businessKey") != null ? params.get("businessKey").toString() : "";

        String deleteReason = params.get("deleteReason") != null ? params.get("deleteReason").toString() : "";

        try {
            this.wfProcessService.deleteProcessByBusinessKey(businessKey, deleteReason, UserUtil.getUser());
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("流程终止失败", e);
            return R.error("终止失败！");
        }
        return R.ok();
    }

    /**
     * 根据流程实例id查询流程处理记录
     *
     * @param processInstanceId
     * @return
     */
    @GetMapping("/getHistoryTaskByProcessInstanceId/{processInstanceId}")
    public R getHistoryTaskByProcessInstanceId(@PathVariable("processInstanceId") String processInstanceId) {
        List<Map<String, Object>> list = this.wfProcessService.getHistoryTaskByProcessInstanceId(processInstanceId);
        return R.ok().put("result", list);
    }

    /**
     * 根据流程实例id查询流程处理记录
     *
     * @param taskId
     * @return
     */
    @GetMapping("/getFileIdByTaskId/{taskId}")
    public R getFileIdByTaskId(@PathVariable("taskId") String taskId) {
        String fileId = this.wfTaskService.getFileIdByTaskId(taskId);
        return R.ok().put("fileId", fileId);
    }

    /**
     * 获取暂存审批意见
     *
     * @param taskId
     * @return
     */
    @GetMapping(value = "/getApproveAdviceByTaskId/{taskId}")
    public R getApproveAdviceByTaskId(@PathVariable("taskId") String taskId) {
        String approveAdvice = this.wfProcessService.getApproveAdviceByTaskId(taskId);
        return R.ok().put("textAdvice", approveAdvice);
    }

    /**
     * 签收
     *
     * @param taskId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/doCliam")
    @ResponseBody
    public R doCliam(@RequestParam("taskId") String taskId, @RequestParam("sign") String sign) throws Exception {
        UserVO user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
        try{
            String assign = "";
            if (sign.equals("0")) {//签发
                this.wfProcessService.doClaim(taskId, null);
            } else {//签收
                this.wfProcessService.doClaim(taskId, user.getId());
                assign = user.getStaffName();
            }
            return R.ok().put("assign", assign);
        }catch(Exception e){
            log.error("处理失败", e);
            return R.error("处理失败");
        }
    }

    /**
     * 根据业务id查询流程处理记录
     *
     * @param params
     * @return
     */
    @GetMapping("/getHistoryTaskByBusinessKey")
    public R getHistoryTaskByBusinessKey(@RequestParam Map<String, Object> params) {
        String businessKey = params.get("businessKey") != null ? params.get("businessKey").toString() : "";
        List<Map<String, Object>> list = this.wfProcessService.getHistoryTaskByBusinessKey(businessKey);
        return R.ok().put("result", list);
    }

    /**
     * 根据流程实例id查询流程定义id
     *
     * @param processInstanceId 流程实例id
     * @return {processDefinitionId:''}
     */
    @GetMapping("/getProcessDefinitionIdByProcessId/{processInstanceId}")
    public R getProcessDefinitionIdByProcessId(@PathVariable("processInstanceId") String processInstanceId) {
        ProcessInstance processInstance = this.wfProcessService.getProcessInstanceById(processInstanceId);
        if(processInstance != null && StringUtils.isNotBlank(processInstance.getProcessDefinitionId())){
        return R.ok().put("processDefinitionId", processInstance.getProcessDefinitionId());
        }else{
            HistoricProcessInstance historicProcessInstance = wfProcessService.getHistoricProcessInstanceById(processInstanceId);
            return R.ok().put("processDefinitionId", historicProcessInstance.getProcessDefinitionId());
        }
    }
    /**
     * 根据流程实例id查询流程处理记录
     *
     * @param processInstanceId
     * @return
     */
    @GetMapping("/getHistoricProcessInstanceById/{processInstanceId}")
    public R getHistoricProcessInstanceById(@PathVariable("processInstanceId") String processInstanceId) {
        HistoricProcessInstance processInstance = this.wfProcessService.getHistoricProcessInstanceById(processInstanceId);

        return R.ok().put("processDefinitionId", processInstance.getProcessDefinitionId());
    }

    /**
     * 根据业务主键查询流程实例及流程参数、当前业务/当前用户的待办任务
     *
     * @param businessKey
     * @return
     */
    @GetMapping("/getWfTaskVoByBusinessKey/{businessKey}")
    public R getProcessInstanceByBusinessKey(@PathVariable("businessKey") String businessKey) {
        UserVO user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
        WfTaskVo wfTaskVo = this.wfTaskService.getWfTaskVoByBusinesskey(businessKey, user);
        return R.ok().put("wfTaskVo", wfTaskVo);
    }

    /**
     * 根据业务主键查询是否在流程中
     *
     * @param businessKey
     * @return
     */
    @GetMapping("/checkByBusinessKey/{businessKey}")
    public R checkByBusinessKey(@PathVariable("businessKey") String businessKey) {
        UserVO user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
        boolean flag = this.wfTaskService.checkByBusinessKey(businessKey, user);
        return R.ok().put("flag", flag);
    }
    
    /**
     * 委托办理
     * @param params {taskId:'', userId}
     * @return
     */
    @PostMapping(value = "/delegateTask")
    public R delegateTask(@RequestBody Map<String, Object> params){
        String taskId = params.containsKey("taskId") ? params.get("taskId").toString().trim() : null;
        String userId = params.containsKey("userId") ? params.get("userId").toString().trim() : null;
        if(StringUtils.isBlank(taskId))
            return R.error("请传入任务ID参数：taskId");
        if(StringUtils.isBlank(userId))
            return R.error("请传入被委派人ID：userId");
        try{
            wfTaskService.delegateTask(taskId, userId);
            return R.ok();
        }catch(Exception e){
            log.error("委派任务失败" , e);
            return R.error("委派任务失败！");
        }
    }
    
    /**
     * 根据任务id获取任务信息
     * @param taskId 任务id
     * @return 任务信息
     */
    @GetMapping(value = "/getTaskInfoById/{taskId}")
    public R getTaskInfoById(@PathVariable("taskId") String taskId) {
        WfTaskVo task = wfTaskService.getTaskInfoById(taskId);
        return R.ok().put("task", task);
    }
    
    /**
     * 根据流程实例id获取任务信息
     * @param processInstanceId 流程实例id
     * @return 流程实例信息
     */
    @GetMapping(value = "/getProcessInstanceById/{processInstanceId}")
    public R getProcessInstanceById(@PathVariable("processInstanceId") String processInstanceId) {
        Map<String, Object> task = wfTaskService.getProcessInstanceById(processInstanceId);
        return R.ok().put("task", task);
    }
    
    /**
     * 根据任务id查询节点是否需要ukey
     * @param taskId 任务id
     * @return needKey
     */
    @GetMapping(value = "/getTaskNeedKey/{taskId}")
    public R getTaskNeedKey(@PathVariable("taskId") String taskId) {
//        String needKey = wfTaskService.getTaskNeedKey(taskId);
        Map<String, String> map = wfTaskService.getTaskNeedKey(taskId);
        return R.ok().put("needKey", map.get("needKey")).put("orgId", map.get("orgId"));
    }

    /**
     * 批量查询节点是否需要ukey
     * @param taskIdArr 任务id
     * @return needKey
     */
    @PostMapping(value = "/getTaskNeedKeyBatch")
    public R getTaskNeedKeyBatch(@RequestBody String[] taskIdArr) {
        Map<String, Map<String, String>> map = wfTaskService.getTaskNeedKeyBatch(taskIdArr);
        return R.ok().put("needKeyMap", map);
    }

    /**
     * 查询第一个节点是否需要ukey
     * @param folderCode 流程目录编码
     * @param orgCode 机构编码
     * @return needKey
     */
    @GetMapping(value = "/getTaskNeedKeyFirst/{folderCode}/{orgCode}")
    public R getTaskNeedKeyFirst(@PathVariable("folderCode") String folderCode, @PathVariable("orgCode") String orgCode){
        String needKey = wfTaskService.getTaskNeedKeyFirst(folderCode, orgCode);
        return R.ok().put("needKey", needKey);
    }
    
    /**
     * 将任务指派给一个人
     * @param taskId 任务id
     * @param userId 用户id
     * @return 结果
     */
    @GetMapping(value = "/resetAssignee/{taskId}/{userId}")
    public R resetAssignee(@PathVariable("taskId") String taskId, @PathVariable("userId") String userId){
        try{
            if(StringUtils.isBlank(userId)){
                return R.error("任务ID不能为空");
            }
            if(StringUtils.isBlank(userId)){
                return R.error("要指派的用户ID不能为空");
            }
            taskService.setAssignee(taskId, userId);
            return R.ok("指派任务成功");
        }catch(Exception e){
            log.error("指派任务失败", e);
            return R.error("指派任务失败");
        }
    }
}
